import axios from 'axios';
import store from '@/store'
// import router from '@/router'
import { Message } from 'element-ui';
// import qs from 'qs';
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 60 * 1000,
  // responseType: "json",
  headers: {
      "Content-Type": "application/json;charset=utf-8",
  },
});

service.interceptors.request.use(
  (config) => {
    // if (config.data) {
    //   config.data = removeNullOrEmpty(config.data);
    // }
    // if (config.params) {
    //   config.params = removeNullOrEmpty(config.params);
    // }
    if (config.headers.contentType === 'formType') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
      // config.data = qs.stringify(config.data);
    }
    //所有都传用户id
    const userId = store.state.user.userInfo?.id
    const userType = store.state.user.userInfo?.userType
    if (userId && config.data && (userType == 1 || userType == 2)) {
      config.data.userId = userId
    }

    // const routerPath = store.state.router.path
    // if ((routerPath == '/probability' || routerPath == '/loseAssess') && config.data) {
    //   config.data.busstype = routerPath == '/probability' ? 1 : 2
    // }
    
    if (config.method.toUpperCase() === 'GET' || config.method.toUpperCase() === 'DELETE') {
			config.params = {
				...config.data,
			}
    }
    if (store.state.user.token) {
      config.headers['X-Access-Token'] = store.state.user.token;
    }
    config.config = {
      showMessage: config.headers.showMessage,
    };
    return config;
  },
  (error) => {
    console.log(error); // for debug
    return Promise.reject(error);
  },
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    // if (response.data.code != 200) {
    if(!response.data.success){
      Message.error(response?.data?.extMessage || response?.data?.message)
      return Promise.reject(new ApiError(response.data.message, response?.data?.result)); 
    } else {
      return response?.data?.result;
    }
    
  },
  (error) => {
    console.dir(error);
    if (error.request.readyState == 4 && error.request.status == 0) {
        error.extMessage = '网络异常，请检查网络';
    }
    const message =
      error?.response?.data?.message ?? error?.extMessage ?? '未知错误';
    const showMessage = error?.response?.config?.config?.showMessage;
    if (showMessage !== false) {
      Message.closeAll();
      Message({
        message,
        type: 'error',
        duration: 3 * 1000,
      });
    }
    // const currentRouter = router.currentRoute
    // const code = error?.response?.data?.code ?? error?.code
    // const needLoginCode = ['TOKEN_HAS_EXPIRED', 'USER_NOT_LOGIN']
    // // 返回以上code需要重新登录
    // if (needLoginCode.includes(code) && currentRouter.path !== '/login') {
    //   store.dispatch('user/resetToken').then(() => {
    //     window.location.reload()
    //   })
    // }
    return Promise.reject(new ApiError(message, error?.response));
  },
);

class ApiError extends Error {
  constructor(message, response) {
    super(message);
    this.message = message;
    this.response = response;
  }
}

export default service;
